using B.S.NewMedical.Api.Read.Application.Command.Order;
using B.S.NewMedical.Api.Read.DTOS;
using B.S.NewMedical.Domain.Order;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.Order
{
    public class ConsultationPageDisplayCommandHandle : IRequestHandler<ConsultationPageDisplayCommand, ApiPageing<ConsultationPageDisplayDto>>
    {
        private readonly IBaseRepository<ConsultationModel> _consultationRepository;
        private readonly ILogger<ConsultationPageDisplayCommandHandle> _logger;

        public ConsultationPageDisplayCommandHandle(
            IBaseRepository<ConsultationModel> consultationRepository,
            ILogger<ConsultationPageDisplayCommandHandle> logger)
        {
            _consultationRepository = consultationRepository;
            _logger = logger;
        }

        public async Task<ApiPageing<ConsultationPageDisplayDto>> Handle(ConsultationPageDisplayCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询问诊单分页显示数据，页码：{Index}，页大小：{Size}", request.Index, request.Size);

                var result = new ApiPageing<ConsultationPageDisplayDto>();

                // 获取所有未删除的问诊单数据
                var query = _consultationRepository.GetAll().Where(x => !x.IsDeleted);

                // 应用查询条件
                if (!string.IsNullOrEmpty(request.Patient))
                {
                    query = query.Where(x => x.Patient != null && x.Patient.Contains(request.Patient));
                }

                if (!string.IsNullOrEmpty(request.Method))
                {
                    query = query.Where(x => x.Method != null && x.Method.Contains(request.Method));
                }

                if (!string.IsNullOrEmpty(request.Source))
                {
                    query = query.Where(x => x.Source != null && x.Source.Contains(request.Source));
                }

                if (!string.IsNullOrEmpty(request.Status))
                {
                    query = query.Where(x => x.Orderstatus != null && x.Orderstatus.Contains(request.Status));
                }

                if (!string.IsNullOrEmpty(request.Orderstatus))
                {
                    query = query.Where(x => x.Orderstatus != null && x.Orderstatus.Contains(request.Orderstatus));
                }

                // 应用排序
                query = ApplySorting(query, request.SortBy, request.SortDirection);

                // 计算总记录数
                var totalCount = await Task.FromResult(query.Count());

                // 计算总页数
                var totalPage = (int)Math.Ceiling(totalCount / (double)request.Size);

                // 应用分页并获取数据
                var consultations = await Task.FromResult(query
                    .Skip((request.Index - 1) * request.Size)
                    .Take(request.Size)
                    .ToList());

                // 转换为显示DTO
                var consultationDisplayDtos = consultations.Select(x => new ConsultationPageDisplayDto
                {
                    Id = x.Id,
                    PatientName = x.Patient,
                    DoctorName = x.Doctor,
                    DepartmentName = x.Department,
                    ConsultationDate = x.ConsultationTime,
                    Method = x.Method,
                    Source = x.Source,
                    ConsultationPrice = x.ConsultationPrices,
                    OrderStatus = x.Orderstatus,
                    CreateTime = x.CreateTime ?? DateTime.Now,
                    UpdateTime = x.UpdateTime ?? DateTime.Now
                }).ToList();

                // 设置状态信息和格式化数据
                foreach (var dto in consultationDisplayDtos)
                {
                    // 设置状态信息
                    SetStatusInfo(dto);
                    
                    // 设置手机号脱敏（暂时设置为空，实际使用时可以从患者表获取）
                    dto.PatientPhoneMasked = "";
                    
                    // 设置格式化时间
                    dto.FormattedConsultationDate = dto.ConsultationDate.ToString("yyyy-MM-dd HH:mm");
                    dto.FormattedCreateTime = dto.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    
                    // 设置是否为新记录和是否过期
                    dto.IsNew = dto.CreateTime >= DateTime.Now.AddDays(-1);
                    dto.IsExpired = dto.CreateTime < DateTime.Now.AddDays(-7);
                }

                // 构建返回结果
                result.Code = ApiEnum.Success;
                result.Msg = "查询问诊单列表成功";
                result.TotaCount = totalCount;
                result.TotaPage = totalPage;
                result.PageData = consultationDisplayDtos;

                _logger.LogInformation("查询问诊单分页显示数据完成，总记录数：{TotalCount}，总页数：{TotalPage}", totalCount, totalPage);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询问诊单分页显示数据时发生错误");
                
                return new ApiPageing<ConsultationPageDisplayDto>
                {
                    Code = ApiEnum.Error,
                    Msg = "查询问诊单列表失败：" + ex.Message,
                    TotaCount = 0,
                    TotaPage = 0,
                    PageData = null
                };
            }
        }

        /// <summary>
        /// 设置状态信息
        /// </summary>
        private void SetStatusInfo(ConsultationPageDisplayDto dto)
        {
            switch (dto.OrderStatus?.ToLower())
            {
                case "待支付":
                    dto.StatusText = "待支付";
                    dto.StatusColor = "warning";
                    break;
                case "已支付":
                    dto.StatusText = "已支付";
                    dto.StatusColor = "success";
                    break;
                case "已取消":
                    dto.StatusText = "已取消";
                    dto.StatusColor = "danger";
                    break;
                case "已完成":
                    dto.StatusText = "已完成";
                    dto.StatusColor = "info";
                    break;
                default:
                    dto.StatusText = dto.OrderStatus ?? "未知";
                    dto.StatusColor = "secondary";
                    break;
            }
        }

        /// <summary>
        /// 应用排序
        /// </summary>
        private IQueryable<ConsultationModel> ApplySorting(IQueryable<ConsultationModel> query, string sortBy, string sortDirection)
        {
            var isDescending = sortDirection?.ToLower() == "desc";

            return sortBy?.ToLower() switch
            {
                "consultationtime" => isDescending 
                    ? query.OrderByDescending(x => x.ConsultationTime)
                    : query.OrderBy(x => x.ConsultationTime),
                "createtime" => isDescending 
                    ? query.OrderByDescending(x => x.CreateTime)
                    : query.OrderBy(x => x.CreateTime),
                "updatetime" => isDescending 
                    ? query.OrderByDescending(x => x.UpdateTime)
                    : query.OrderBy(x => x.UpdateTime),
                "patient" => isDescending 
                    ? query.OrderByDescending(x => x.Patient ?? "")
                    : query.OrderBy(x => x.Patient ?? ""),
                "doctor" => isDescending 
                    ? query.OrderByDescending(x => x.Doctor ?? "")
                    : query.OrderBy(x => x.Doctor ?? ""),
                "department" => isDescending 
                    ? query.OrderByDescending(x => x.Department ?? "")
                    : query.OrderBy(x => x.Department ?? ""),
                _ => query.OrderByDescending(x => x.ConsultationTime) // 默认按问诊时间倒序
            };
        }
    }
} 